package com.example.tacocloud.controller;

import com.example.tacocloud.bean.Order;
import com.example.tacocloud.bean.Taco;
import com.example.tacocloud.bean.User;
import com.example.tacocloud.configue.OrderProps;
import com.example.tacocloud.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/orders")
@SessionAttributes("order")
public class OrderController {
    @Autowired
    private OrderMapper om;

    @Autowired
    private OrderProps op;

    @GetMapping("/current")
    public String orderForm(@AuthenticationPrincipal User user, @ModelAttribute Order order){
        if (order.getDeliveryName() == null){
            order.setDeliveryName(user.getFullName());
        }
        if (order.getDeliveryStreet() == null){
            order.setDeliveryStreet(user.getStreet());
        }
        if (order.getDeliveryCity() == null){
            order.setDeliveryCity(user.getCity());
        }
        if (order.getDeliveryState() == null){
            order.setDeliveryState(user.getState());
        }
        if (order.getDeliveryZip() == null){
            order.setDeliveryZip(user.getZip());
        }
        return "orderForm";
    }

    @PostMapping
    public String processOrder(@Valid Order order, Errors errors
                               , SessionStatus sessionStatus,
                               @AuthenticationPrincipal User user){
        if (errors.hasErrors()) {
            return "orderForm";
        }
        order.setPlacedAt(new Date());
        order.setUser(user);
        om.saveOrderDetails(order);
        long orderId = om.findOrderId(order.getDeliveryName());
        order.setId(orderId);

        List<Taco> tacos = order.getTacos();
        for (Taco taco:tacos){
            om.saveTacoToOrder(orderId, taco.getId());
        }
        sessionStatus.setComplete();
//        log.info("Order submitted: " + order);
        return "redirect:/";
    }

    @GetMapping
    public String ordersForUser(@AuthenticationPrincipal User user, Model model){
        List<Order> orders = om.findOrdersByUserId(user.getId(), op.getPageSize());
        log.error("ordersForUser: " + orders);
        model.addAttribute("orders", orders);

        return "orderList";
    }
}
